package com.example.img_factory


import android.content.pm.PackageManager
import android.graphics.*
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.FileNotFoundException as FileNotFoundException1


class MainActivity : AppCompatActivity() {

    var btn:Button?=null
    var outputBtn:Button?=null
    var img:ImageView?=null
    var img2:ImageView?=null
    var editText:EditText?=null
    var xNUmberText:EditText?=null
    var yNUmberText:EditText?=null
    var fontSizeText:EditText?=null
    var littleFontSizeText:EditText?=null
    var paint:Paint = Paint()
    var littlePaint:Paint = Paint()

    var imgName:String = "battery_level"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        PermissionUtils.isGrantExternalRW(this, 1);//检查是否具有权限
        btn = findViewById(R.id.start_btn)
        outputBtn = findViewById(R.id.output)

        img = findViewById(R.id.img)
        img2 = findViewById(R.id.img2)

        editText = findViewById(R.id.text)
        xNUmberText = findViewById(R.id.xNumber)
        yNUmberText = findViewById(R.id.yNumber)
        fontSizeText = findViewById(R.id.font_szie)
        littleFontSizeText = findViewById(R.id.little_text_size)
        btn?.setOnClickListener {
            setImg()
        }
        outputBtn?.setOnClickListener {
            outputImg()
        }
        img?.setOnClickListener {
            imgName = "battery_level"
            Toast.makeText(this,"切换图片成功",Toast.LENGTH_SHORT).show()
        }
        img2?.setOnClickListener {
            imgName = "battery_level_check"
            Toast.makeText(this,"切换图片成功",Toast.LENGTH_SHORT).show()
        }
        initPaint()
        setImg()
    }


    fun initPaint(){
        val typeface = Typeface.createFromAsset(this.getAssets(), "BebasKai.ttf")

        paint.isAntiAlias = true;
        paint.setTypeface(typeface)
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(10f);
        paint.textSize = 24f

        littlePaint.isAntiAlias = true;
        littlePaint.setTypeface(typeface)
        littlePaint.setColor(Color.WHITE);
        littlePaint.setStrokeWidth(10f);
        littlePaint.textSize = 24f
    }

    fun setImg(){
        val bitmap = PermissionUtils.getImageFromAssetsFile(this,"$imgName.png");
        var canvas =  Canvas(bitmap)

        val fontSize = fontSizeText?.text.toString().toFloat()
        paint.textSize = fontSize
        val littleFontSize = littleFontSizeText?.text.toString().toFloat()
        littlePaint.textSize = littleFontSize

        val input = editText?.text.toString()
        val xNum = xNUmberText?.text.toString().toInt()
        val yNum = yNUmberText?.text.toString().toInt()

        val measureText:Float = paint.measureText(input)
        val x = bitmap.width / 2 - xNum - measureText/2
        val y = bitmap.height / 2 - yNum

        val littleX = x+measureText+2
        val littleY = y + 0

        canvas.drawText(input, x.toFloat(), y.toFloat(), paint);
        canvas.drawText("%",littleX,littleY.toFloat(),littlePaint)

        if(imgName === "home_location"){
            img?.setImageBitmap(bitmap)
        }else{
            img2?.setImageBitmap(bitmap)
        }
    }

    fun outputImg(){
        val mybitmap = PermissionUtils.getImageFromAssetsFile(this,"$imgName.png");
        val fontSize = fontSizeText?.text.toString().toFloat()
        paint.textSize = fontSize
        val littleFontSize = littleFontSizeText?.text.toString().toFloat()
        littlePaint.textSize = littleFontSize
        val xNum = xNUmberText?.text.toString().toInt()
        val yNum = yNUmberText?.text.toString().toInt()
        val x = mybitmap.width / 2 - xNum
        val y = mybitmap.height / 2 - yNum
        var job = GlobalScope.launch(Dispatchers.Main) {
            draw(101,mybitmap,paint,x.toFloat(),y.toFloat());
            Log.d("----------","输出完成")
        }
    }

    suspend fun draw(count:Int,bitmap:Bitmap,paint: Paint,x:Float,y:Float){
        for (index in 0 until count){
            val bm =  bitmap.copy(Bitmap.Config.ARGB_8888,true);
            val canvas =  Canvas(bm)
            val measureText:Float = paint.measureText(index.toString())
            val numberX = x - measureText/2
            val littleX = numberX+measureText+2
            val littleY = y
            canvas.drawText(index.toString(),numberX,y,paint)
            canvas.drawText("%",littleX,littleY,littlePaint)
            saveBitmap("${imgName}_${index}.png", bm)
        }
    }

    /** 保存方法  */
    fun saveBitmap(fileName: String, bm: Bitmap) {

        val targetPath: String =  Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/images/$imgName/"
        Log.d("targetPath", targetPath)

        val dir = File(targetPath)
        if(!dir.exists()){
            dir.mkdirs()
        }
        val f = File(targetPath, fileName)
        if (f.exists()) {
            f.delete()
        }
        try {
            val out = FileOutputStream(f)
            bm.compress(Bitmap.CompressFormat.PNG, 100, out)
            out.flush()
            out.close()
        } catch (e: FileNotFoundException1) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


    override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<out String>,
            grantResults: IntArray
    ) {
        when (requestCode) {
            1 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //检验是否获取权限，如果获取权限，外部存储会处于开放状态，会弹出一个toast提示获得授权
                val sdCard = Environment.getExternalStorageState()
                if (sdCard == Environment.MEDIA_MOUNTED) {
                    Toast.makeText(this, "获得授权", Toast.LENGTH_LONG).show()
                }
            } else {
                runOnUiThread {
                    Toast.makeText(
                            this,
                            "您未授权存储权限将无法保存图片",
                            Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions!!, grantResults)
    }

}